package demo1;

import java.util.Arrays;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-04-30
 * Time: 10:15
 */
public class MyStack {
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_SIZE = 10;

    public MyStack() {
        this.elem = new int[DEFAULT_SIZE];
    }

    private boolean isFull() {
        return usedSize == elem.length;
    }
    // 压栈
    public int push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize++] = val;
        return val;
    }

    // 出栈
    public int  pop() {
        if(Empty()) {
            throw new RuntimeException("栈为空, 无法出栈!");
        }
        // 弹的是栈顶元素, 从 0 下标开始, 则为 usedSIze - 1 因此需要先 -- 在使用
        return elem[--usedSize];

    }

    // 栈是否为空
    public boolean Empty() {
        return usedSize == 0;
    }

    // 拿栈顶元素
    public int peek() {
        if(Empty()) {
            throw new RuntimeException("栈为空!");
        }
        return elem[usedSize - 1];

    }
}
